package ar.uba.fi.posgrado.economy.web.action.account;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ar.uba.fi.posgrado.economy.service.CustomerService;
import ar.uba.fi.posgrado.economy.model.Customer;
import ar.uba.fi.posgrado.economy.model.Debt;
import ar.uba.fi.posgrado.economy.model.DebtStatus;
import ar.uba.fi.posgrado.economy.service.DebtService;
import ar.uba.fi.posgrado.economy.web.form.customer.CustomerAccountForm;

/**
 * 
 * @author pablo.tortorella
 * 
 */
public class ShowCustomerAccountAction extends Action {

	private DebtService debtService;

	private CustomerService customerService;

	/**
	 * @return the customerService
	 */
	public CustomerService getCustomerService() {
		return customerService;
	}

	/**
	 * @param customerService
	 *            the customerService to set
	 */
	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	/**
	 * @return the debtService
	 */
	public DebtService getDebtService() {
		return debtService;
	}

	/**
	 * @param debtService
	 *            the debtService to set
	 */
	public void setDebtService(DebtService debtService) {
		this.debtService = debtService;
	}

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		CustomerAccountForm form = (CustomerAccountForm) actionForm;
		Long customerId = form.getCustomerId();

		// busco el cliente
		Customer customer = customerService.getById(customerId);

		Debt debt = new Debt();
		debt.setCustomer(customer);
		List<DebtStatus> status = new ArrayList<DebtStatus>();
		status.add(DebtStatus.Active);
		status.add(DebtStatus.Vencida);
		status.add(DebtStatus.Balanced);
		
		// busco las deudas activas y vencidas (o sea, las cobrables) del cliente
		List<Debt> customerDebts = debtService.getDebtsByConditions(debt, status);

//		// sumo el total para mostrar
//		Double totalDebt = 0d;
//		for (Debt debt : customerDebts) {
//			totalDebt += debt.getBalance();
//		}

		form.setAccountId(customer.getAccount().getId());
		form.setBalance(customer.getAccount().getInFavorCredit());
		form.setTotalDebt(customer.getAccount().getTotalDebt());
		form.setCustomerId(customer.getId());
		form.setCustomerName(customer.getCorporateName());
		form.setActiveDebts(customerDebts);

		return mapping.findForward("success");
	}

}
